package cn.tedu.account.tcc;

import cn.tedu.account.entity.Account;
import cn.tedu.account.mapper.AccountMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
@Component
public class AccountTccActionImpl implements AccountTccAction {
    @Autowired
    private AccountMapper accountMapper;
    @Transactional
    @Override
    public synchronized boolean prepare(BusinessActionContext ctx, Long userId, BigDecimal money) {
        //判断是否有足够的金额
        Account account = accountMapper.selectByUserId(userId);
        if (account.getResidue().compareTo(money) < 0) {
            throw new RuntimeException("可用金额不足");
        }
        //冻结金额
        accountMapper.updateResidueToFrozen(userId, money);
        //第一阶段的成功标记
        ResultHolder.setResult(AccountTccAction.class,ctx.getXid(),"p");
        return true;
    }
    @Transactional
    @Override
    public synchronized boolean commit(BusinessActionContext ctx) {
        //判断一阶段成功标记是否存在
        if (ResultHolder.getResult(AccountTccAction.class,ctx.getXid()) == null) {
            return true;
        }
        //上下文对象取出参数，执行提交
        Long userId = Long.valueOf(ctx.getActionContext("userId").toString());
        BigDecimal money = new BigDecimal(ctx.getActionContext("money").toString());
        accountMapper.updateFrozenToUsed(userId, money);
        //提交完成后，删除标记
        ResultHolder.removeResult(AccountTccAction.class,ctx.getXid());
        return true;
    }
    @Transactional
    @Override
    public synchronized boolean rollback(BusinessActionContext ctx) {
        //判断一阶段成功标记是否存在
        if (ResultHolder.getResult(AccountTccAction.class,ctx.getXid()) == null) {
            return true;
        }
        //上下文对象取出参数，执行提交
        Long userId = Long.valueOf(ctx.getActionContext("userId").toString());
        BigDecimal money = new BigDecimal(ctx.getActionContext("money").toString());
        accountMapper.updateFrozenToResidue(userId, money);
        //提交完成后，删除标记
        ResultHolder.removeResult(AccountTccAction.class,ctx.getXid());
        return true;
    }
}
